package com.dailyblue.java.spring.boot.security.handler;

import com.alibaba.fastjson.JSONArray;
import com.dailyblue.java.spring.boot.commons.util.JsonResult;
import com.dailyblue.java.spring.boot.commons.util.ResultCode;
import com.dailyblue.java.spring.boot.commons.util.ResultTool;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Component
@Slf4j
public class NotLoginHandler implements AuthenticationEntryPoint {

    // 会在用户未登陆，访问资源时自动执行
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        log.info("用户没有登陆");
        response.setContentType("application/json;charset=utf-8");
        PrintWriter out = response.getWriter();
        JsonResult result = ResultTool.fail(ResultCode.USER_NOT_LOGIN);
        out.println(JSONArray.toJSONString(result));
    }
}
